﻿using Casamiel.Domain.Entity;

using Smooth.IoC.UnitOfWork.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Linq;
using Casamiel.Domain;

namespace Casamiel.Infrastructure.Repositories
{
    public class MbrStoreRepository : BaseRepository<StoreEntity, int>, IMbrStoreRepository
    {
        public MbrStoreRepository(IDbFactory factory) : base(factory)
        {
        }

        public async Task<List<StoreEntity>> GeRectRangeAsync<TSession>(double minLat, double minLng, double maxLat, double maxLng) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
		        var list = await session.QueryAsync<StoreEntity>($"SELECT * FROM {Sql.Table<StoreEntity>(session.SqlDialect)} WHERE   isClose=0  and  Latitude>= @minLat AND Latitude < @maxLat AND Longitude >=@minLng AND Longitude<@maxLng", new { minLat, maxLat, minLng, maxLng }).ConfigureAwait(false);
                return list.ToList();
            }
        }

        /// <summary>
        /// Gets the name of the store by.
        /// </summary>
        /// <returns>The store by name.</returns>
        /// <param name="StoreName">Store name.</param>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="pageSize">Page size.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
		public async Task<PagingResult<StoreEntity>> GetStoreByName<TSession>(string StoreName, int pageIndex, int pageSize) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                PagingResult<StoreEntity> result = new PagingResult<StoreEntity>
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
                int total = 0;
                var sql = GetSelectSQL($"{Sql.Table<StoreEntity>(session.SqlDialect)}", $" (storeName like @StoreName or FullAddress like @FullAddress) and isClose=0  ", "storeId desc", pageIndex, pageSize);
				string countsql = $"select count(0) from {Sql.Table<StoreEntity> (session.SqlDialect)}  where  (storeName like @StoreName or FullAddress like @FullAddress) and isClose=0  ";
                //if (!string.IsNullOrEmpty(StoreName))
                //{
                //    countsql += $"and (storeName like '%{StoreName.Replace("'", "''",StringComparison.CurrentCultureIgnoreCase)}%' or FullAddress like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%')";
                //}

                total = await session.QueryFirstAsync<int>(countsql,new { StoreName="%"+ StoreName +"%", FullAddress = "%"+ StoreName + "%"}).ConfigureAwait(false);
                var list = await session.QueryAsync<StoreEntity>(sql.Item1, new { StoreName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%", begin = sql.Item2, end = sql.Item3 }).ConfigureAwait(false);
                result.Data = list.ToList();
                result.Total = total;
                return result;
            }
        }

        public async Task<PagingResult<StoreEntity>> GetTakeOutStoreByNameAsync<TSession>(string StoreName, int pageIndex, int pageSize) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                PagingResult<StoreEntity> result = new PagingResult<StoreEntity>
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize
                };
                int total = 0;
                var sql = GetSelectSQL($"{Sql.Table<StoreEntity>(session.SqlDialect)}", $" (storeName like @storeName  or FullAddress like @FullAddress) and isClose=0 and iswaimaiClose=0 ", "storeId desc", pageIndex, pageSize);
                string countsql = $"select count(0) from {Sql.Table<StoreEntity>(session.SqlDialect)}  where (storeName like @storeName  or FullAddress like @FullAddress) and isClose=0 and iswaimaiClose=0 ";
                //if (!string.IsNullOrEmpty(StoreName))
                //{
                //    countsql += $"and (storeName like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%' or FullAddress like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%')";
                //}

                total = await session.QueryFirstAsync<int>(countsql, new { storeName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%" }).ConfigureAwait(false);
                var list = await session.QueryAsync<StoreEntity>(sql.Item1, new { storeName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%" ,begin = sql.Item2, end = sql.Item3 }).ConfigureAwait(false);
                result.Data = list.ToList();
                result.Total = total;
                return result;
            }
        }

        /// <summary>
        /// Gets the store by name async.
        /// </summary>
        /// <returns>The store by name async.</returns>
        /// <param name="StoreName">Store name.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<List<StoreEntity>>GetStoreByNameAsync<TSession>(string StoreName) where TSession:class,ISession{
            using (var session = Factory.Create<TSession>())
            {
				string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)}  where (storeName like @storeName  or FullAddress like @FullAddress) and IsCakeClose=0 ";
                //if (!string.IsNullOrEmpty(StoreName))
                //{
                //    sql += $"and (storeName like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%' or FullAddress like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%')";
                //}
                var list = await session.QueryAsync<StoreEntity>(sql,new { storeName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%" }).ConfigureAwait(false);
                return list.ToList();
            }

        }
        /// <summary>
        /// Gets all store by name async.
        /// </summary>
        /// <returns>The all store by name async.</returns>
        /// <param name="StoreName">Store name.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<List<StoreEntity>> GetAllStoreByNameAsync<TSession>(string StoreName) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)} where storeName like @storeName  or  FullAddress like @FullAddress";
                //if (!string.IsNullOrEmpty(StoreName))
                //{
                //    sql += $" where  (storeName like '%{StoreName.Replace("'", "''",StringComparison.CurrentCultureIgnoreCase)}%' or FullAddress like '%{StoreName.Replace("'", "''", StringComparison.CurrentCultureIgnoreCase)}%')";
                //}
                var list = await session.QueryAsync<StoreEntity>(sql, new { storeName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%" }).ConfigureAwait(false);
                return list.ToList();
            }

        }

        public async Task<List<StoreEntity>> GetListAsync<TSession>(string StoreName,int IsShow) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)}   where IsShow=@IsShow  and ( storeName like @storeName  or  FullAddress like @FullAddress)";
                //if (!string.IsNullOrEmpty(StoreName))
                //{
                //    sql += $" and   (storeName like '%{StoreName.Replace("'", "''",StringComparison.CurrentCultureIgnoreCase)}%' or FullAddress like '%{StoreName.Replace("'", "''",StringComparison.CurrentCultureIgnoreCase)}%')";
                //}
                var list = await session.QueryAsync<StoreEntity>(sql,new { IsShow, storeName = "%" + StoreName + "%", FullAddress = "%" + StoreName + "%" }).ConfigureAwait(false);
                return list.ToList();
            }

        }


        /// <summary>
        /// Gets the by store identifier async.
        /// </summary>
        /// <returns>The by store identifier async.</returns>
        /// <param name="StoreId">Store identifier.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<StoreEntity> GetByStoreIdAsync<TSession>(int StoreId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)} where StoreId=@StoreId";
                return await session.QueryFirstOrDefaultAsync<StoreEntity>(sql, new { StoreId })
                    .ConfigureAwait(false);
            }
        }

        public async Task<StoreEntity> GetByRelationIdAsync<TSession>(int RelationId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)} where RelationId=@RelationId";
                return await session.QueryFirstOrDefaultAsync<StoreEntity>(sql, new { RelationId })
                    .ConfigureAwait(false);
            }
        }

        public async Task<StoreEntity> GetByELEStoreIdAsync<TSession>(string ELEStoreId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select * from { Sql.Table<StoreEntity>(session.SqlDialect)} where ELEStoreId=@ELEStoreId";
                return await session.QueryFirstOrDefaultAsync<StoreEntity>(sql, new { ELEStoreId })
                    .ConfigureAwait(false);
            }
        }

    }
}
